package org.fightingliu.demo.config;

import org.fightingliu.demo.handler.RedisMessageHandler;
import org.fightingliu.demo.listener.RedisSubscriber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : LiuChao
 * @description : TODO
 * @date : 2025-04-16 21:52:05
 */
@Configuration
@ConditionalOnBean({RedisMessageHandler.class,RedisSubscriber.class})
public class RedisConfig {

    @Autowired
    private List<RedisMessageHandler> messageHandlers = new ArrayList<>();

    @Bean
    public Map<String, RedisMessageHandler> redisMessageHandlerMap(){
        //转换为map，当出现转换错误，考虑是否RedisMessageHandler实现类getTopic方法是否配置异常
        return messageHandlers.stream().collect(Collectors.toMap(RedisMessageHandler::getTopic, RedisMessageHandler->RedisMessageHandler));
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter(RedisSubscriber redisSubscriber) {
        return new MessageListenerAdapter(redisSubscriber);
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(
            RedisConnectionFactory connectionFactory, MessageListenerAdapter messageListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        List<ChannelTopic> channelTopicList = messageHandlers.stream().map(redisMessageHandler -> ChannelTopic.of(redisMessageHandler.getTopic())).collect(Collectors.toList());
        container.addMessageListener(messageListenerAdapter, channelTopicList);
        return container;
    }
}
